import Mock from 'mockjs';

// 设置延迟时间和响应类型
Mock.setup({
  timeout: '200-600',
  responseType: 'json'
});

// 菜单数据
const menuList = [
  {
    id: 1,
    name: '仪表盘',
    path: '/dashboard',
    icon: 'dashboard',
    parentId: 0,
    order: 1,
    status: 1
  },
  {
    id: 2,
    name: '系统管理',
    path: '/system',
    icon: 'setting',
    parentId: 0,
    order: 2,
    status: 1
  },
  {
    id: 3,
    name: '菜单管理',
    path: '/system/menu',
    icon: 'menu',
    parentId: 2,
    order: 1,
    status: 1
  },
  {
    id: 4,
    name: '用户管理',
    path: '/system/user',
    icon: 'user',
    parentId: 2,
    order: 2,
    status: 1
  },
  {
    id: 5,
    name: '角色管理',
    path: '/system/role',
    icon: 'team',
    parentId: 2,
    order: 3,
    status: 1
  },
  {
    id: 6,
    name: '个人中心',
    path: '/profile',
    icon: 'user',
    parentId: 0,
    order: 3,
    status: 1
  }
];

// 获取菜单列表 - 使用字符串路径而不是正则表达式
Mock.mock('/api/menus', 'get', {
  code: 200,
  message: '获取成功',
  data: menuList
});

// 添加菜单
Mock.mock('/api/menus', 'post', (options) => {
  try {
    const body = JSON.parse(options.body);
    const newMenu = {
      id: Mock.Random.id(),
      ...body,
      status: body.status || 1
    };
    menuList.push(newMenu);
    return {
      code: 200,
      message: '添加成功',
      data: newMenu
    };
  } catch (error) {
    console.error('解析请求体失败:', error);
    return {
      code: 400,
      message: '请求格式错误',
      data: null
    };
  }
});

// 更新菜单 - 使用函数而不是正则表达式
Mock.mock((url) => url.includes('/api/menus/') && url.match(/\/\d+$/), 'put', (options) => {
  try {
    const id = parseInt(options.url.split('/').pop());
    const body = JSON.parse(options.body);
    const index = menuList.findIndex(item => item.id === id);
    
    if (index !== -1) {
      menuList[index] = { ...menuList[index], ...body };
      return {
        code: 200,
        message: '更新成功',
        data: menuList[index]
      };
    }
    
    return {
      code: 404,
      message: '菜单不存在',
      data: null
    };
  } catch (error) {
    console.error('处理更新请求失败:', error);
    return {
      code: 400,
      message: '请求格式错误',
      data: null
    };
  }
});

// 删除菜单 - 使用函数而不是正则表达式
Mock.mock((url) => url.includes('/api/menus/') && url.match(/\/\d+$/), 'delete', (options) => {
  try {
    const id = parseInt(options.url.split('/').pop());
    const index = menuList.findIndex(item => item.id === id);
    
    if (index !== -1) {
      const deletedMenu = menuList.splice(index, 1)[0];
      return {
        code: 200,
        message: '删除成功',
        data: deletedMenu
      };
    }
    
    return {
      code: 404,
      message: '菜单不存在',
      data: null
    };
  } catch (error) {
    console.error('处理删除请求失败:', error);
    return {
      code: 400,
      message: '请求格式错误',
      data: null
    };
  }
});

export default Mock;